package gc3d.database;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;

// http://java.sun.com/javase/6/docs/api/java/util/UUID.html
public abstract class GridDB implements Serializable, Cloneable {
	private static final long serialVersionUID = 1L;
	private String host;
	private String username;
	private String password;
	private Connection con;

	public GridDB(String host, String username, String password) throws ClassNotFoundException {
		this.host = host;
		this.username = username;
		this.password = password;
		this.con = null;
	}

	// db methods
	private void open() throws SQLException, ClassNotFoundException {
		Class.forName("org.hsqldb.jdbcDriver");
		con = DriverManager.getConnection(host, username, password);
	}

	private void close() throws SQLException {
		con.close();
		con = null;
	}

	public ResultSet query(String query) {
		try {
			this.open();
			try {
				Statement state = con.createStatement();
				return state.executeQuery(query);
			} finally {
				this.close();
			}
		} catch (SQLException e) {
			System.err.println("[ERROR][db] query("+query+") SQLException "+e.getMessage());
		} catch (ClassNotFoundException e) {
			System.err.println("[ERROR][db] query("+query+") ClassNotFoundException "+e.getMessage());
		}
		return null;
	}

	public int update(String query) {
		try {
			this.open();
			try {
				Statement state = con.createStatement();
				return state.executeUpdate(query);
			} finally {
				this.close();
			}
		} catch (SQLException e) {
			System.err.println("[ERROR][db] update("+query+") SQLException "+e.getMessage());
		} catch (ClassNotFoundException e) {
			System.err.println("[ERROR][db] update("+query+") ClassNotFoundException "+e.getMessage());
		}
		return -1;
	}

	public static String now() {
	    Calendar cal = Calendar.getInstance();
	    // TODO see java.sql.Date
	    // http://java.developpez.com/faq/jdbc/?page=types
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
	    return sdf.format(cal.getTime());
	}

	@Override
	public GridDB clone() {
		GridDB cloneGridDB = null;
		try {
			cloneGridDB          = (GridDB) super.clone();
			cloneGridDB.host     = new String(this.host);
			cloneGridDB.username = new String(this.username);
			cloneGridDB.password = new String(this.password);
			cloneGridDB.con      = null;
		} catch (CloneNotSupportedException cnse) {
			cnse.printStackTrace();
		}
		return cloneGridDB;
	}
}
